var wsSearch = {
	wsUri : ws_server,
	websocket : null,
	callBack : null,
	SearchText : null,
	SearchPath : null,
	Search : function(searchPath, searchText, callBackFunc) {
		debugger;
		wsSearch.SearchText = searchText;
		wsSearch.SearchPath = searchPath;
		wsSearch.callBack = callBackFunc;
		wsSearch.websocket = new WebSocket(this.wsUri);
		wsSearch.RegisterEvent();
	},

	RegisterEvent : function() {

		wsSearch.websocket.onopen = function(evt) {
			wsSearch.onOpen(evt);
		};
		wsSearch.websocket.onclose = function(evt) {
			// alert("close?");
			wsSearch.onClose(evt);
		};
		wsSearch.websocket.onmessage = function(evt) {
			wsSearch.onMessage(evt);
		};
		wsSearch.websocket.onerror = function(evt) {
			wsSearch.onError(evt);
		};
	},

	onOpen : function(evt) {
		console.log('CONNECTED');
		debugger;
		var a = new Array();
		var path = {
			key : 'path',
			value : wsSearch.SearchPath,
		};
		a.push(path);
		var data = {
			key : 'text',
			value : wsSearch.SearchText,
		};
		a.push(data);

		wsSearch.doSend(JSON.stringify(a));
		// '[{"key":"1","value":"3333"}]');
	},
	onClose : function(evt) {
		console.log("DISCONNECTED");
	},

	onMessage : function(evt) {
		console.log("receive data:" + evt.data);
		wsSearch.callBack(evt.data);
	},

	onError : function(evt) {
		console.log("onError:" + evt);
	},

	doSend : function(message) {
		wsSearch.websocket.send(message);
	},
};
var tinybook = {
	init : function() {
		this.loadData('');
		this.loadStatic();
		$('#txtSearch').keydown(
				function(e) {
					var curKey = e.which;
					if (curKey == 13) {
						wsSearch.Search('/', $('#txtSearch').val(),
								tinybook.HandleSearchResult);
					}
				});
		$('#btnSearch').click(this.SearchFunc);
	},
	HandleSearchResult : function(result) {
		// debugger;
		console.log("enter , receive msg from server,msg:" + result);
		var retObj = jQuery.parseJSON(result);
		if (retObj.ResultType == 0) {
			$('#msg').html(retObj.Description);
		} else {
			debugger;
			$('#msg').html(
					'搜索耗时' + retObj.Description + '毫秒，搜索结果：'
							+ retObj.BookList.length);
			if (retObj.BookList.length != 0) {
				// console.log(retObj.BookList[0].BookName);
				var result = tinybook.ParseQueryResult('', retObj.BookList)
				// $('#dirList').html(result.dirInnerHtml);
				$('#bookList').html(result.fileInnerHtml);
			}
		}
	},

	SearchFunc : function() {
		wsSearch.Search($('', '#txtSearch').val(), tinybook.HandleSearchResult);
	},
	// <a href="http://www.bootcdn.cn/bootstrap/"
	// class="package list-group-item" data-library-name="bootstrap"
	// target="_blank"
	// onclick="_hmt.push([&#39;_trackEvent&#39;, &#39;packages&#39;,
	// &#39;click&#39;, &#39;bootstrap&#39;])"
	// style="display: block;">
	FileParse : function(row) {
		var downLoadIcon = '<a href="/down?dir=' + row.Path + '&file='
				+ row.BookName
				+ '" title="点击下载此文件"><img style="width:50px;" src="'
				+ this.RootPath() + '/svg/download.svg"/></a>';
		var downTag = '<a href="/down?dir=' + row.Path + '&file='
				+ row.BookName + '" title="点击下载此文件">' + row.BookName + '</a>';
		var catgory = '分类：';
		if (row.Path.length == 0 || row.Path == "." || row.Path == "./"
				|| row.Path == "/") {
			catgory += '推荐';
		} else {
			catgory += row.Path;
		}

		var htmlText = '<div class="row">'
				+ '<div class="col-xs-2 col-md-2 text-center">'
				+ '<h4 class="package-name">'
				// + row.Path
				// + '<br/>'
				+ downLoadIcon
				+ '</h4></div>'
				+ '<div class="col-xs-9 col-md-9">'
				+ '<p class="package-description">'
				+ downTag
				+ '<br/>'
				+ catgory
				+ '</p></div>'
				+ '<div class="package-extra-info col-xs-9 col-md-9 col-md-offset-2 col-xs-12">'
				+ '<span><i class="fa fa-star"></i> ' + row.FileSize
				+ '</span>' + '</div></div></a> ';

		return htmlText;
	},

	loadStatic : function() {
		var url = this.RootPath() + '/global';
		this.Ajax(url, null, function(result) {
			debugger;
			$('#fileCount').html(result.FileCount);
			$('#fileSize').html(tinybook.toByteDesc(result.FileSize));
		});
	},
	toByteDesc : function(FileSize) {
		if (FileSize < 1000000) {
			return (FileSize.toPrecision() / 1000).toFixed(3) + "KB";
		} else if (FileSize > 1000000 && FileSize < 1000000000) {
			return (FileSize.toPrecision() / 1000000).toFixed(3) + "MB";
		} else {
			return (FileSize.toPrecision() / 1000000000).toFixed(3) + "GB";
		}
	},
	loadData : function(dir) {
		debugger;
		var url = this.RootPath() + '/list?dir=' + dir;
		this.Ajax(url, null, function(rows) {
			debugger;
			// 处理目录层级
			var dirInnerHtml = tinybook.ParseDirectory(dir);
			var result = tinybook.ParseQueryResult(dirInnerHtml, rows)
			$('#dirList').html(result.dirInnerHtml);
			$('#bookList').html(result.fileInnerHtml);
		});
	},

	// 处理目录层级结构
	ParseDirectory : function(dir) {
		var dirs = dir.split("/");
		debugger;
		var fullPath = "";
		var dirInnerHtml = '<button type="button" class="btn btn-default" onclick="tinybook.loadData(\'\')">首页</button>';
		for (var i = 0; i < dirs.length; i++) {
			if (dirs[i].length > 0 && dirs[i] != "." && dirs[i] != "/") {
				if (fullPath.length == 0) {
					fullPath += '/';
				}
				fullPath += dirs[i];

				dirInnerHtml += '<button type="button" class="btn btn-default" onclick="tinybook.loadData(\''
						+ fullPath + '\')">' + dirs[i] + '</button>';
			}
		}
		return dirInnerHtml;
	},
	// 处理server返回的查询结果
	ParseQueryResult : function(dirInnerHtml, rows) {
		var fileInnerHtml = '';

		// 处理本级目录和查询结果文件
		var localDirHtml = '';
		var localDirHtmlPre = '<div class="btn-group" role="group">'
				+ '<button type="button" class="btn btn-default dropdown-toggle"'
				+ 'data-toggle="dropdown" aria-haspopup="true"'
				+ 'aria-expanded="false">'
				+ ' 查看本级目录 <span class="caret"></span>'
				+ ' </button> <ul class="dropdown-menu">';
		for (var i = 0; i < rows.length; i++) {
			console.log('rows index:' + i);
			if (rows[i].Type == 0) {
				localDirHtml += tinybook.DirParse(rows[i])
			} else {
				fileInnerHtml += tinybook.FileParse(rows[i])
			}
		}

		// 拼装目录层级和本机目录集合
		if (localDirHtml.length > 0) {
			dirInnerHtml += localDirHtmlPre + localDirHtml + "</ul></div>";
		}
		return {
			fileInnerHtml : fileInnerHtml,
			dirInnerHtml : dirInnerHtml
		};
	},

	DirParse : function(row) {
		var htmlText = '<li><a href="javascript:void" onclick="tinybook.loadData(\''
				+ row.Path
				+ '/'
				+ row.BookName
				+ '\')">'
				+ row.BookName
				+ '</a></li>';
		return htmlText;
	},
	RootPath : function() {

		var strFullPath = window.document.location.href;
		var strPath = window.document.location.pathname;
		if (strPath.length == 1) {
			return strFullPath.substring(0, strFullPath.length - 1);
		}
		var pos = strFullPath.indexOf(strPath);
		var prePath = strFullPath.substring(0, pos);
		var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
		return (prePath + postPath);
	},
	Ajax : function(url, aData, successFunc) {
		var aType = 'get';
		var callType = 'json';

		if ((url.indexOf('http://') < 0 || url.indexOf('https://') < 0)
				&& url.indexOf(this.RootPath()) < 0) {
			callType = 'jsonp';
		}
		// debugger;
		var r = parseInt(Math.random() * 100);
		try {
			var result = $.ajax({
				type : aType,
				url : url,
				data : aData,
				contentType : "application/json",
				async : false,
				dataType : callType,
				jsonpCallback : 'mycallback' + r,
				success : successFunc,
				error : function(jqXHR, textStatus, errorThrown) {
					console.log('网络故障！<br/>' + url);
					alert('网络异常！');
				},
			}).fail(function(jqXHR, textStatus, errorThrown) {

				console.log("catch exception:" + errorThrown);
			});
		} catch (ex) {
			console.log("catch exception :" + ex);
		}
		console.log("url:" + url + ",result:" + result);
	},
};

// 页面加载完毕后，初始化
$(function() {
	tinybook.init();
});